<template>
  <div class="roles">
   <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色</el-breadcrumb-item>
    </el-breadcrumb>
     <!-- 按钮 -->
    <el-button type="success" class="addBtn" @click="showAddDailog" plain>添加角色</el-button>
    <!-- 角色列表 -->
    <el-table :data="roleList"  >
      <el-table-column  type="index" label="#"></el-table-column>
      <el-table-column  type="expand" >
        <template v-slot:default="{row}">
          <p v-if="row.children.length===0">暂无权限</p>
          <!-- 一级权限 -->
          <el-row v-for="item1 in row.children" :key="item1.id" class="item1" @close="delRight(row,item1.id)">
          <el-col  :span="4">
            <el-tag  type="primary" closable>{{item1.authName}}</el-tag>
            <i class="el-icon-arrow-right"></i>
          </el-col>
          <el-col :span="20">
            <!-- 二级渲染 -->
            <el-row v-for="item2 in item1.children" :key="item2.id" class="item2" @close="delRight(row,item2.id)">
              <el-col :span="4">
                <el-tag  type="success" closable>{{item2.authName}}</el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <el-col :span="20">
                <!-- 三级渲染 -->
                <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable class="item3" @close="delRight(row,item3.id)">{{item3.authName}}</el-tag>
              </el-col>
            </el-row>
          </el-col>
         </el-row>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName" ></el-table-column>
      <el-table-column label="描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
           <template v-slot:default='{ row }'>
           <el-button type="primary" size="small" plain  icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
           <el-button type="danger"  size="small" plain icon="el-icon-delete" @click="deleteRoles(row.id)" ></el-button>
           <el-button type="success"  size="small" plain icon="el-icon-check" @click="showRightsDialog(row)">分配权限</el-button>
           </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限模态框 -->
    <el-dialog
     title="分配权限"
     :visible.sync="dialogVisible"
     width="30%"
    >
    <!-- 树形结构图 -->
  <el-tree :data="rightsList" show-checkbox node-key="id" :props="treeProps"
  default-expand-all ref="tree"
  ></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="assignRights">分 配</el-button>
  </span>
</el-dialog>
    <!-- 添加模态框 -->
    <el-dialog title="添加角色"
    :visible.sync="addDialogVisible"
    @close="closeAddDialog"
    width="30%">
      <el-form :model="addForm" ref="form" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </template>
    <!-- 修改模态框 -->
  </el-dialog>
    <el-dialog title="修改角色"
    :visible.sync="editDialogVisible"
    width="30%">
      <el-form :model="editForm" ref="editForm" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoles">确 定</el-button>
        </span>
      </template>
  </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getRoleList()
  },
  data () {
    return {
      // 标记正在操作的角色id
      roleId: '',
      // 所有权限列表
      rightsList: [],
      // 角色列表
      roleList: [],
      // 默认勾选的节点的 key 的数组
      defaultKeys: [],
      addDialogVisible: false,
      dialogVisible: false,
      editDialogVisible: false,
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      rules: {
        roleName: [
          { required: true, message: '内容不能为空', trigger: ['change', 'blur'] }
        ],
        roleDesc: [
          { required: true, message: '内容不能为空', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  methods: {
    // 封装函数渲染页面
    async getRoleList () {
      const { meta, data } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.roleList = data
        console.log(data)
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 删除指定权限
    async delRight (row, rightId) {
      const { meta, data } = await this.$axios.delete(`roles/${row.id}/rights/${rightId}`)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        row.children = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 分配权限模态框显示
    async showRightsDialog (row) {
      this.dialogVisible = true
      // 获取当前的角色id
      this.roleId = row.id
      console.log('this', this.roleId)

      // 展开前获取所有权限数据
      const { data, meta } = await this.$axios.get(`rights/tree`)
      if (meta.status === 200) {
        // console.log(data)
        this.$message.success(meta.msg)
        this.rightsList = data
        // 获取三级的id
        const ids = []
        row.children.forEach(l1 => {
          l1.children.forEach(l2 => {
            l2.children.forEach(l3 => {
              ids.push(l3.id)
              // console.log(ids)
            })
          })
        })
        this.$refs.tree.setCheckedKeys(ids)
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 分配权限
    async assignRights () {
      // 获取全选和半选的ID
      const halfIds = this.$refs.tree.getHalfCheckedKeys()
      const allIds = this.$refs.tree.getCheckedKeys()
      const rids = [...halfIds, ...allIds].join(',')
      // console.log(rids)
      const { meta } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.dialogVisible = false
        this.getRoleList()
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 添加模态框的显示
    showAddDailog () {
      this.addDialogVisible = true
    },
    // 添加角色
    async addRoles () {
      try {
        await this.$refs.form.validate()
        const { meta } = await this.$axios.post('roles', this.addForm)
        // console.log(meta)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.addDialogVisible = false
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 关闭模态框 重置内容
    async closeAddDialog () {
      await this.$refs.form.resetFields()
    },
    // 删除角色
    async deleteRoles (id) {
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '温馨提示', { type: 'warning' })
      const { meta } = await this.$axios.delete(`roles/${id}`)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.getRoleList()
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 修改模态框的显示 回显
    showEditDialog (row) {
      this.editDialogVisible = true
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
      this.editForm.id = row.id
    },
    // 修改角色
    async editRoles () {
      await this.$refs.editForm.validate()
      const { id, roleDesc, roleName } = this.editForm
      const { meta } = await this.$axios.put(`roles/${id}`, { roleDesc, roleName })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.editDialogVisible = false
        this.getRoleList()
      } else {
        this.$message.error(meta.msg)
      }
    }

  }
}
</script>

<style lang="scss">
.roles{
 .addBtn{
margin-bottom: 10px;
}
}
.item1{
   padding: 5px;
  margin-bottom: 5px;
  border-bottom: 1px dotted #ccc;
}
.item2{
  margin-bottom: 5px;
}
.item3{
  margin-bottom: 5px;
}

</style>
